package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(value = "/registerServlet")
public class RegisterServlet extends HttpServlet {
    //新建service对象,用于调用方法
    private final UserService service =new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //    封装数据
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
    //    获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
    //    系统生成的验证码，从session中获取
        HttpSession session = request.getSession();
        //object-->string
       String checkCodeGen = (String) session.getAttribute("checkCodeGen");
        //比较验证码是否一致，忽略大小写
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){
        //设置错误信息
            request.setAttribute("register_msg","验证码错误！");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        //    不允许注册
            return;
        }
        //     调用注册方法
        boolean flag = service.register(user);
    if (flag){
    //   成功。跳转登陆页面
        request.setAttribute("register_msg", "注册成功，请登录！");
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }else {
    //    注册失败。跳转注册页面
        request.setAttribute("register_msg", "用户名已存在！");
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
